package services

import (
	"dake-farmer-home/internal/models"
	"dake-farmer-home/internal/pkg/configs"
	"dake-farmer-home/internal/repositories"
	"dake-farmer-home/internal/tools/strs"
	"dake-farmer-home/internal/tools/validates"
	"errors"
)

type userService struct{}

var UserService = newUserService()

func newUserService() *userService {
	return &userService{}
}

func (s *userService) Login(account, password string) (*models.User, error) {
	if strs.IsBlank(account) {
		return nil, errors.New("账号名不能为空")
	}
	err := validates.ValidatePassword(password)
	if err != nil {
		return nil, err
	}

	user := repositories.UserRepository.GetByAccount(configs.DB(), account)
	if user == nil {
		return nil, errors.New("找不到用户")
	}

	if password != user.Password {
		return nil, errors.New("密码错误")
	}

	return user, nil

}

func (s *userService) Register(account, password string) (*models.User, error) {
	if strs.IsBlank(account) {
		return nil, errors.New("账号名不能为空")
	}
	err := validates.ValidatePassword(password)
	if err != nil {
		return nil, err
	}

	user := repositories.UserRepository.GetByAccount(configs.DB(), account)
	if user != nil {
		return nil, errors.New("账号名已存在")
	}
	user = &models.User{
		Account:  account,
		Password: password,
	}
	err = repositories.UserRepository.Create(configs.DB(), user)
	if err != nil {
		return nil, err
	}
	return user, nil
}
